<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { getUserInfo, setUserInfo } from '@/utils/auth';
import { getUserProfile, updateUserProfile } from '@/api/user';
import BaseLayout from '@/views/layout/BaseLayout.vue';

// 导入组件
import ProfileSidebar from '@/components/profile/ProfileSidebar.vue';
import ProfileForm from '@/components/profile/ProfileForm.vue';
import SecurityForm from '@/components/profile/SecurityForm.vue';
import NotificationSettings from '@/components/profile/NotificationSettings.vue';
import AlertMessage from '@/components/profile/AlertMessage.vue';
import GlobalStyles from '@/components/profile/GlobalStyles.vue';

// 获取用户信息
const currentUserInfo = getUserInfo() || {};
const isLoaded = ref(false);
const activeSection = ref('profile');
const showSuccessMessage = ref(false);
const showErrorMessage = ref(false);
const errorMessage = ref('');
const isLoading = ref(false); // 添加加载状态

// 用户头像
const userAvatar = ref(currentUserInfo.avatar || '');
// 新选择的头像文件
const avatarFile = ref(null);
// 头像预览数据 (用于本地预览，不发送到服务器)
const avatarPreview = ref('');
// 服务器存储的头像URL
const avatarUrl = ref(currentUserInfo.avatarUrl || currentUserInfo.avatar || '');

// 对话框状态
const showConfirmDialog = ref(false);

// 表单数据
const formData = reactive({
  username: currentUserInfo.username || '',
  lastName: '',
  firstName: '',
  email: '',
  phone: '',
  nationality: '',
  gender: '',
  travelPreference: '',
  language: 'zh'
});

// 表单验证规则
const validateForm = () => {
  if (!formData.username.trim()) {
    errorMessage.value = '用户名不能为空';
    showErrorMessage.value = true;
    return false;
  }
  
  if (formData.email && !isValidEmail(formData.email)) {
    errorMessage.value = '请输入有效的邮箱地址';
    showErrorMessage.value = true;
    return false;
  }
  
  if (formData.phone && !isValidPhone(formData.phone)) {
    errorMessage.value = '请输入有效的手机号码';
    showErrorMessage.value = true;
    return false;
  }
  
  return true;
};

// 邮箱验证
const isValidEmail = (email) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
};

// 手机号验证
const isValidPhone = (phone) => {
  const phoneRegex = /^1[3-9]\d{9}$/;
  return phoneRegex.test(phone);
};

// 保存防抖处理
let saveTimeout = null;

// 保存用户信息
const saveUserInfo = async () => {
  // 防抖处理
  if (saveTimeout) {
    clearTimeout(saveTimeout);
  }
  
  saveTimeout = setTimeout(async () => {
    // 重置消息状态
    showSuccessMessage.value = false;
    showErrorMessage.value = false;
    
    if (!validateForm()) {
      return;
    }
    
    isLoading.value = true;
    
    try {
      // 准备请求数据
      const requestData = {
        username: formData.username,
        lastName: formData.lastName,
        firstName: formData.firstName,
        email: formData.email,
        phone: formData.phone,
        nationality: formData.nationality,
        gender: formData.gender,
        preferredLanguage: formData.language,
        // 如果有新选择的头像，使用base64编码数据，否则使用现有URL
        avatarUrl: avatarPreview.value || avatarUrl.value
      };
      
      console.log('正在保存用户数据:', requestData);
      
      // 调用API保存用户信息
      const response = await updateUserProfile(requestData);
      console.log('更新用户信息响应：', response);
      
      if (response.data && response.data.code === 200) {
        // API调用成功，更新本地存储
        const updatedUserInfo = {
          ...currentUserInfo,
          username: formData.username,
          lastName: formData.lastName,
          firstName: formData.firstName,
          email: formData.email,
          phone: formData.phone,
          nationality: formData.nationality,
          gender: formData.gender,
          preferredLanguage: formData.language,
          avatarUrl: avatarPreview.value || avatarUrl.value // 保存头像数据
        };
        
        // 将预览数据保存到URL变量中，因为现在它们都是base64编码
        if (avatarPreview.value) {
          avatarUrl.value = avatarPreview.value;
        }
        
        // 清除头像文件缓存，但保留base64数据
        avatarFile.value = null;
        avatarPreview.value = '';
        
        setUserInfo(updatedUserInfo);
        showSuccessMessage.value = true;
        errorMessage.value = "个人信息已成功更新！";
        
        // 3秒后隐藏成功消息
        setTimeout(() => {
          showSuccessMessage.value = false;
        }, 3000);
      } else {
        // API调用失败，显示错误信息
        errorMessage.value = response.data?.message || '保存信息失败，请稍后再试';
        showErrorMessage.value = true;
      }
    } catch (error) {
      console.error('保存用户信息出错:', error);
      
      // 根据错误类型提供更详细的错误信息
      if (error.response) {
        // 服务器返回了错误状态码
        if (error.response.status === 401) {
          errorMessage.value = '登录已过期，请重新登录';
        } else if (error.response.status === 403) {
          errorMessage.value = '您没有权限执行此操作';
        } else if (error.response.status === 400) {
          errorMessage.value = error.response.data?.message || '请求数据格式不正确';
        } else if (error.response.status === 500) {
          errorMessage.value = '服务器内部错误，请稍后再试';
        } else {
          errorMessage.value = error.response.data?.message || '保存信息失败，请稍后再试';
        }
      } else if (error.request) {
        // 请求已发送但没有收到响应
        errorMessage.value = '网络连接失败，请检查您的网络连接';
      } else {
        // 发送请求时出现错误
        errorMessage.value = '保存失败，请稍后再试';
      }
      
      showErrorMessage.value = true;
    } finally {
      isLoading.value = false;
      saveTimeout = null;
    }
  }, 300); // 300ms的防抖延迟
};

// 重置表单
const resetForm = () => {
  formData.username = currentUserInfo.username || '';
  formData.lastName = currentUserInfo.lastName || '';
  formData.firstName = currentUserInfo.firstName || '';
  formData.email = currentUserInfo.email || '';
  formData.phone = currentUserInfo.phone || '';
  formData.nationality = currentUserInfo.nationality || '';
  formData.gender = currentUserInfo.gender || '';
  formData.language = currentUserInfo.preferredLanguage || 'zh';
  
  // 重置头像为当前用户头像
  avatarUrl.value = currentUserInfo.avatarUrl || currentUserInfo.avatar || '';
  avatarPreview.value = ''; // 清除预览数据
  avatarFile.value = null;
  
  showErrorMessage.value = false;
  showSuccessMessage.value = false;
};

// 上传头像
const handleAvatarUpload = () => {
  // 创建文件输入元素
  const fileInput = document.createElement('input');
  fileInput.type = 'file';
  fileInput.accept = 'image/*';
  
  // 监听文件选择
  fileInput.addEventListener('change', (e) => {
    if (e.target.files && e.target.files.length > 0) {
      const file = e.target.files[0];
      
      // 文件类型检查
      if (!file.type.startsWith('image/')) {
        errorMessage.value = '请选择图片文件';
        showErrorMessage.value = true;
        return;
      }
      
      // 文件大小检查 (限制为2MB)
      if (file.size > 2 * 1024 * 1024) {
        errorMessage.value = '图片大小不能超过2MB';
        showErrorMessage.value = true;
        return;
      }
      
      // 保存文件引用，等待与表单一起提交
      avatarFile.value = file;
      
      // 为用户提供预览
      const reader = new FileReader();
      reader.onload = (event) => {
        avatarPreview.value = event.target.result;
      };
      reader.readAsDataURL(file);
      
      showSuccessMessage.value = true;
      errorMessage.value = "头像已选择，点击保存更改按钮完成提交";
      setTimeout(() => {
        showSuccessMessage.value = false;
      }, 3000);
    }
  });
  
  // 触发文件选择
  fileInput.click();
};

// 用户点击保存按钮
const handleSaveClick = () => {
  saveUserInfo();
};

onMounted(async () => {
  isLoading.value = true;
  
  try {
    // 调用API获取用户信息
    const response = await getUserProfile();
    console.log('获取用户信息响应：', response);
    
    // 处理API返回的数据
    if (response.data && response.data.code === 200) {
      const userData = response.data.data;
      
      // 更新表单数据
      formData.username = userData.username || currentUserInfo.username || '';
      
      // 直接从用户数据中获取字段，而不是从profile对象
      formData.lastName = userData.lastName || '';
      formData.firstName = userData.firstName || '';
      formData.email = userData.email || '';
      formData.phone = userData.phone || '';
      formData.nationality = userData.nationality || '';
      formData.gender = userData.gender || '';
      formData.language = userData.preferredLanguage || 'zh';
      
      // 获取头像数据 - 现在是base64格式
      if (userData.avatarUrl) {
        avatarUrl.value = userData.avatarUrl;
      }
    } else {
      // 如果API调用失败，尝试使用本地存储的用户信息
      // 尝试直接从currentUserInfo获取
      formData.lastName = currentUserInfo.lastName || '';
      formData.firstName = currentUserInfo.firstName || '';
      formData.email = currentUserInfo.email || '';
      formData.phone = currentUserInfo.phone || '';
      formData.nationality = currentUserInfo.nationality || '';
      formData.gender = currentUserInfo.gender || '';
      formData.language = currentUserInfo.preferredLanguage || 'zh';
      
      // 如果还是找不到，再尝试旧的profile结构
      if (currentUserInfo.profile) {
        if (!formData.lastName) formData.lastName = currentUserInfo.profile.lastName || '';
        if (!formData.firstName) formData.firstName = currentUserInfo.profile.firstName || '';
        if (!formData.email) formData.email = currentUserInfo.profile.email || '';
        if (!formData.phone) formData.phone = currentUserInfo.profile.phone || '';
        if (!formData.nationality) formData.nationality = currentUserInfo.profile.nationality || '';
        if (!formData.gender) formData.gender = currentUserInfo.profile.gender || '';
        if (formData.language === 'zh') formData.language = currentUserInfo.profile.language || 'zh';
      }
      
      // 获取头像
      if (currentUserInfo.avatarUrl) {
        avatarUrl.value = currentUserInfo.avatarUrl;
      } else if (currentUserInfo.avatar) {
        // 兼容旧数据
        avatarUrl.value = currentUserInfo.avatar;
      }
      
      // 如果API返回了错误消息，可以选择显示
      if (response.data?.message) {
        console.warn('获取用户信息失败：', response.data.message);
      }
    }
  } catch (error) {
    console.error('获取用户信息出错:', error);
    
    // 发生错误时尝试从本地用户信息直接获取
    formData.lastName = currentUserInfo.lastName || '';
    formData.firstName = currentUserInfo.firstName || '';
    formData.email = currentUserInfo.email || '';
    formData.phone = currentUserInfo.phone || '';
    formData.nationality = currentUserInfo.nationality || '';
    formData.gender = currentUserInfo.gender || '';
    formData.language = currentUserInfo.preferredLanguage || 'zh';
    
    // 再尝试旧的profile结构
    if (currentUserInfo.profile) {
      if (!formData.lastName) formData.lastName = currentUserInfo.profile.lastName || '';
      if (!formData.firstName) formData.firstName = currentUserInfo.profile.firstName || '';
      if (!formData.email) formData.email = currentUserInfo.profile.email || '';
      if (!formData.phone) formData.phone = currentUserInfo.profile.phone || '';
      if (!formData.nationality) formData.nationality = currentUserInfo.profile.nationality || '';
      if (!formData.gender) formData.gender = currentUserInfo.profile.gender || '';
      if (formData.language === 'zh') formData.language = currentUserInfo.profile.language || 'zh';
    }
  } finally {
    isLoading.value = false;
    
    // 设置页面加载状态，触发动画
    setTimeout(() => {
      isLoaded.value = true;
    }, 300);
  }
});
</script>

<template>
  <BaseLayout>
    <!-- 引入全局样式组件 -->
    <GlobalStyles />
    
    <div class="profile-container" :class="{ 'loaded': isLoaded }">
      <div class="profile-header">
        <h1 class="page-title">个人信息</h1>
        <p class="page-subtitle">管理您的个人资料和账户信息</p>
      </div>
      
      <!-- 加载状态指示器 -->
      <div v-if="isLoading" class="loading-overlay">
        <div class="loading-spinner">
          <i class="fas fa-circle-notch fa-spin"></i>
          <span>加载中...</span>
        </div>
      </div>
      
      <div class="profile-content">
        <!-- 使用侧边栏组件，传递头像URL -->
        <ProfileSidebar 
          :activeSection="activeSection"
          :avatar="avatarPreview || avatarUrl"
          @update:activeSection="activeSection = $event"
          @avatar-upload="handleAvatarUpload"
        />
        
        <div class="profile-form">
          <!-- 使用消息提示组件 -->
          <AlertMessage 
            type="success" 
            :message="errorMessage" 
            :show="showSuccessMessage" 
          />
          
          <AlertMessage 
            type="error" 
            :message="errorMessage" 
            :show="showErrorMessage" 
          />
          
          <!-- 根据活动菜单项显示不同的表单组件 -->
          <!-- 个人资料 -->
          <ProfileForm 
            v-if="activeSection === 'profile'" 
            :formData="formData"
            @update:formData="newData => Object.assign(formData, newData)"
            @save="handleSaveClick"
            @reset="resetForm"
          />
          
          <!-- 账户安全 -->
          <SecurityForm v-if="activeSection === 'security'" />
          
          <!-- 通知设置 -->
          <NotificationSettings v-if="activeSection === 'notifications'" />
        </div>
      </div>
    </div>
  </BaseLayout>
</template>

<style scoped>
/* 增加样式权重，确保样式正确应用 */
.profile-container {
  max-width: 1200px;
  margin: 40px auto;
  padding: 0 20px;
  opacity: 0.1; /* 改为0.1，确保内容在动画失败时仍然可见 */
  transform: translateY(20px);
  transition: all 0.5s ease;
  position: relative; /* 添加相对定位，为加载指示器做准备 */
}

.profile-container.loaded {
  opacity: 1 !important; /* 增加!important确保样式权重 */
  transform: translateY(0) !important;
}

/* 加载状态指示器样式 */
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
  border-radius: 12px;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  color: #00c389;
}

.loading-spinner i {
  font-size: 3rem;
}

.loading-spinner span {
  font-size: 1rem;
  font-weight: 500;
}

.profile-header {
  margin-bottom: 30px;
  text-align: center;
  animation: fadeIn 0.8s ease-out forwards;
}

@keyframes fadeIn {
  0% {
    opacity: 0.1;
    transform: translateY(-20px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

.page-title {
  font-size: 2.4rem !important; /* 增加!important确保样式权重 */
  color: #333;
  margin-bottom: 10px;
}

.page-subtitle {
  color: #666;
  font-size: 1.1rem;
}

.profile-content {
  display: flex !important; /* 确保flex布局生效 */
  gap: 30px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.profile-form {
  flex-grow: 1;
  padding: 30px;
}

@media (max-width: 992px) {
  .profile-content {
    flex-direction: column !important;
  }
}

@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
    gap: 0;
  }
  
  .payment-buttons {
    flex-direction: column;
  }
  
  .add-payment-btn {
    width: 100%;
  }
}
</style> 